package cn.edu.tsinghua.cic.ccss.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.forten.core.ro.DtoResultWithPageInfo;
import org.forten.dataio.excel.ExcelUtil;
import org.forten.dataio.excel.exporter.Excel2003Exporter;
import org.forten.dataio.excel.exporter.Excel2007Exporter;
import org.forten.dataio.excel.exporter.ExcelExporter;
import org.forten.utils.collection.CollectionUtil;
import org.forten.utils.common.StringUtil;
import org.forten.utils.system.LogUtil;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.edu.tsinghua.cic.ccss.bo.CadreBo;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4Export;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4Import;
import cn.edu.tsinghua.cic.ccss.qo.CadreListQo;

@Controller
@Scope("prototype")
@RequestMapping("cadre")
@SessionAttributes("cadreListQo")
public class CadreAction extends SuperAction {
	private static Logger log = Logger.getLogger(CadreAction.class);
	private static final String CADRE_QUERY_MSG = "干部信息查询:%s";
	private static final String CADRE_DELETE_MSG = "干部信息删除:%s";

	@Resource(name = "cadreBo")
	private CadreBo cadreBo;
	@Resource(name = "cadreListQo")
	private CadreListQo cadreListQo;
	private String message = null;

	@RequestMapping("gotoCadreList")
	public String gotoCadreList(Model model) {
		model.addAttribute("cadreListQo", cadreListQo);
		return "forward:showCadreList.jspx";
	}

	@RequestMapping("showCadreList")
	public String showCadreList(Model model,
			@ModelAttribute("cadreListQo") CadreListQo cadreListQo,
			@RequestParam(defaultValue = "1") int pageNo) {
		LogUtil.debug(log, CADRE_QUERY_MSG, cadreListQo.toString());

		DtoResultWithPageInfo<CadreDto> dtos = this.cadreBo.queryCadreDtoPage(
				cadreListQo, pageNo);
		model.addAttribute("dto", dtos.getResults());
		model.addAttribute("page", dtos.getPageInfo());
		model.addAttribute("cadreListQo", cadreListQo);
		return "cadre/gbxxList";
	}

	@RequestMapping("gotoCadreEdit")
	public String gotoCadreEdit(Model model, @RequestParam Long id) {
		CadreDto cadreDto = this.cadreBo.loadCadreDto(id);
		model.addAttribute("editDto", cadreDto);
		return "cadre/editgbxx";
	}

	@RequestMapping("editCadre")
	public String editCadre(Model model,
			@ModelAttribute("editDto") CadreDto cadreDto) {
		try {
			cadreBo.doUpdate(cadreDto);
			message = "编辑信息操作成功";
		} catch (HibernateOptimisticLockingFailureException e) {
			message = "编辑信息操作失败：提交数据时被编辑的干部信息可能已经被其它用户修改，请重新操作。";
		}
		model.addAttribute("message", message);
		return "forward:showCadreList.jspx";
	}

	@RequestMapping("gotoCadreAdd")
	public String gotoAddCadre(Model model) {
		model.addAttribute("addDto", new CadreDto());
		return "cadre/addgbxx";
	}

	@RequestMapping("addCadre")
	public String addCadre(Model model,
			@ModelAttribute("addDto") CadreDto cadreDto) {
		String msg = cadreBo.doSave(cadreDto);
		if (StringUtil.hasText(msg)) {
			model.addAttribute("errMsg", "干部信息添加失败：" + msg);
			return "error-msg";
		}
		message = "新增信息操作成功";
		model.addAttribute("message", message);
		return "forward:showCadreList.jspx";
	}

	@RequestMapping("deleteCadre")
	public String deleteCadre(Model model,
			@RequestParam(defaultValue = "") Long id) {
		LogUtil.debug(log, CADRE_DELETE_MSG);
		CadreDto cadreDto = this.cadreBo.loadCadreDto(id);
		if (cadreDto != null && cadreDto.getCardNum() != null) {
			this.cadreBo.doDeleteEntity(id);
			message = "删除操作成功！";
		} else {
			message = "删除失败，非法ID";
		}

		model.addAttribute("message", message);
		cadreListQo.clean();
		return "redirect:gotoCadreList.jspx";
	}

	@RequestMapping("export2003")
	public void export2003(HttpServletResponse response,
			@ModelAttribute("cadreListQo") CadreListQo cadreListQo) {
		List<CadreDto4Export> result = cadreBo.export(cadreListQo);
		ExcelExporter export = new Excel2003Exporter();
		Workbook wb = export.export(result);
		ExcelUtil.downloadFile(response, wb,
				"CadreListInfo" + export.getPostfix());
	}

	@RequestMapping("export2007")
	public void export2007(HttpServletResponse response,
			@ModelAttribute("cadreListQo") CadreListQo cadreListQo) {
		List<CadreDto4Export> result = cadreBo.export(cadreListQo);
		ExcelExporter export = new Excel2007Exporter();
		Workbook wb = export.export(result);
		ExcelUtil.downloadFile(response, wb,
				"CadreListInfo" + export.getPostfix());
	}

	@RequestMapping("gotoUploadCadreData")
	public String gotoUploadCadreData() {
		return "cadre/upload";
	}

	@RequestMapping("uploadData")
	public String uploadData(Model model, HttpServletRequest request) {
		List<CadreDto4Import> list = null;
		try {
			list = ExcelUtil.uploadFile(request, CadreDto4Import.class, 1);
		} catch (Exception e) {
			List<String> msg = new ArrayList<String>();
			msg.add("导入文件格式有误：" + e.getMessage());
			model.addAttribute("errMsg", msg);
			model.addAttribute("url", "../cadre/gotoUploadCadreData.jspx");
			return "error-msg";
		}
		List<String> errMsg = cadreBo.doBatchImport(list);
		if (!CollectionUtil.isEmpty(errMsg)) {
			model.addAttribute("errMsg", errMsg);
			model.addAttribute("url", "../cadre/gotoUploadCadreData.jspx");
			return "error-msg";
		}
		return "redirect:gotoCadreList.jspx";
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				new SimpleDateFormat("yyyy-MM"), true));
	}
}
